<template>
    <div>

         </div>
</template>


<script>
import {defineComponent} from 'vue'
import DateUtil from "@/utils/dateUtil";
import childComment from "./childComment.vue";

export default defineComponent({
    name: "ProductInfo",
    components: {
        childComment
    },
    data() {
        return {
            commentProductId: '',
            textarea: '',
            parentId: '',  //  parent_id
            rootParentId: '',  //  root_parent_id
            commentList: [],
            circleUrl: "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png",


            account: {},
            userId: '',
            favoriteId: '',
            favorite: {},
            productId: '',
            product: {},
            store: {},
            storeId: '',
            quantity: 1,            // 购买的数量
            maxQuantity: 10,
            numberStatus: false,
            isFavorite: false,
            activeName: 'first',
            cartId: '',
            cart: {},


        }
    },
    mounted() {
        // 进入页面就加载用户信息
        this.account = JSON.parse(localStorage.getItem('account'))
        this.userId = this.account.id
        this.productId = this.$route.query.id
        this.commentProductId = this.productId

        // 跳转到该页面时候未携带参数，则返回
        if (this.productId === '' || this.productId === undefined || this.productId === null) {
            this.goBack()
            return
        }
        this.loadProductAndStore()
        this.checkFavorite()

        this.loadCommentList()
        // console.log(this.maxQuantity)

    },
    methods: {

        // 发送评论
        sendComment() {
            // 评论内容         从输入框获取
            // 用户id          从本地获取
            // 发布时间         后端生成
            // is_delete        0
            // productId       从return获取商品id
            // 父评论id        父评论就是从点击回复里面获取的      如果存在，那么就在return中
            // 根评论id        从 父评论 中获取 根评论id         如果存在，那么就在return中

            if (this.userId === null || this.userId === '' || this.userId === undefined) {
                this.$message.info('请先登录')
                this.$router.push('/login')
                return
            }
            if (this.productId === null || this.productId === '' || this.productId === undefined) {
                this.$message.info('商品不存在')
                this.$router.go(-1)
            }

            let comment = {}
            comment.content = this.textarea
            comment.userId = this.userId
            comment.isDelete = 0
            comment.productId = this.productId
            comment.parentId = this.parentId
            comment.rootParentId = this.rootParentId
            console.log(comment);
            this.$request.post('/comment/add', comment).then(res => {
                if (res.code === '200') {
                    this.$message.success('评论成功')
                    this.loadCommentList()
                    this.textarea = ''
                    this.cancelComment()
                } else {
                    this.$message.error(res.msg)
                }
            })
        },
        // 子组件返回值
        handleMessageFromChild(data) {
            console.log('父组件接收到数据：')
            console.log(data);
            this.parentId = data.parentId
            this.rootParentId = data.rootParentId
            this.commentProductId = data.productId
        },
        // 回复设置
        replyComment(comment) {
            this.parentId = comment.id
            this.rootParentId = comment.rootParentId
            this.commentProductId = comment.productId
            console.log(this.parentId)
            console.log(this.rootParentId)
            console.log(this.commentProductId)
        },
        // 取消回复
        cancelComment() {
            this.parentId = ''
            this.rootParentId = ''
            this.commentProductId = this.productId
            console.log(this.parentId)
            console.log(this.rootParentId)
        },
        // 删除评论
        deleteComment(comment) {
            // 直接删除这个评论就行，实体类
            console.log(comment)
            this.$request.post('/comment/delete', comment).then(res => {
                if (res.code === '200') {
                    this.$message.success('删除成功')
                    this.loadCommentList()
                } else {
                    this.$message.error(res.msg)
                }
            })
        },
        // 加载评论
        loadCommentList() {
            this.$request.get('/comment/list' + '?productId=' + this.productId).then(res => {
                if (res.code == '200') {
                    this.commentList = res.data.commentList
                    console.log(this.commentList)
                } else {
                    this.$message.error(res.msg)
                }
            })
        },

        checkFavorite() {
            this.$request.post('/userFavoriteProduct/checkFavoriteByUserIdAndProductId?userId=' + this.userId + '&productId=' + this.productId).then(res => {
                if (res.code === '200') {
                    if (res.data === null || res.data === undefined || res.data === '') {
                        this.isFavorite = false
                    } else {
                        this.favoriteId = res.data.id
                        this.favorite = res.data
                        this.isFavorite = true
                    }
                    // console.log(this.favoriteId)
                    // console.log(this.favorite)
                } else {
                    this.$message.error(res.msg)
                }
            })
        },

        loadStore() {
            this.$request.get('/store/storeInfo?id=' + this.product.storeId).then(res => {
                if (res.code === '200') {
                    this.store = res.data
                    // console.log(this.store)
                } else {
                    this.$message.error(res.msg)
                }
            })
        },

        loadProductAndStore() {
            this.$request.get('/product/productInfo?id=' + this.productId).then(res => {
                if (res.code === '200') {
                    this.product = res.data
                    this.storeId = this.product.storeId
                    // console.log(this.product)
                    if (this.product.stock <= 0) {
                        console.log('库存不足')
                        this.numberStatus = true
                    } else {
                        this.numberStatus = false
                    }
                    // 优化：购买的最大数量
                    this.maxQuantity = this.product.stock > 10 ? 10 : this.product.stock
                    this.loadStore()
                } else {
                    this.$message.error(res.msg)
                }
            })
        },

        goBack() {
            this.$router.go(-1)
        },

        addToCart() {
            let cart = {}
            cart.userId = this.userId
            cart.productId = this.productId
            cart.quantity = this.quantity
            cart.status = 1
            cart.total = this.product.price * this.quantity
            cart.createTimeStr = DateUtil.formatDate(new Date())
            cart.updateTimeStr = DateUtil.formatDate(new Date())
            this.$request.post('/cart/add', cart).then(res => {
                if (res.code === '200') {
                    this.$message.success('添加成功')
                } else {
                    this.$message.error(res.msg)
                }
            })


        },

        buyNow() {
            if (this.productId === '' || this.productId === null || this.productId === undefined) {
                this.$router.push(this.$route.matched[0].path)
                return
            }
            let cart = {}
            cart.userId = this.userId
            cart.productId = this.productId
            cart.quantity = this.quantity
            cart.status = 3
            cart.total = this.product.price * this.quantity
            cart.createTimeStr = DateUtil.formatDate(new Date())
            cart.updateTimeStr = DateUtil.formatDate(new Date())
            this.$request.post('/cart/createCart', cart).then(res => {
                // console.log(res)
                if (res.code === '200') {
                    this.cart = res.data
                    this.cartId = this.cart.id
                    // 跳转到结算页面
                    let ids = [this.cartId]
                    this.$router.push({name: 'checkoutPage', params: {num: ids}})
                } else {
                    this.$message.error(res.msg)
                }
            })


        },

        changeFavorite() {
            if (this.isFavorite) {
                // 取消收藏
                this.$request.delete('/userFavoriteProduct/deleteById/' + this.favoriteId).then(res => {
                    if (res.code === '200') {
                        this.$message.success('取消收藏成功')
                        this.checkFavorite()
                    } else {
                        this.$message.error(res.msg)
                    }
                })
            } else {
                // 收藏
                this.$request.post('/userFavoriteProduct/add?userId=' + this.userId + '&productId=' + this.productId).then(res => {
                    if (res.code === '200') {
                        this.$message.success('收藏成功')
                        this.checkFavorite()
                    } else {
                        this.$message.error(res.msg)
                    }
                })
            }
        },

        toStoreInfo() {
            this.$router.push('/storeInfo?id=' + this.storeId)
        },

        handleClick(tab, event) {
            console.log(tab.name);
            if (tab.name === 'second') {
                this.loadCommentList()
            }
        }
    }
})
</script>


<style scoped>

</style>